﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using mmCore.Classes;
using mmCore.Common;

namespace mmImdbProvider
{
    public class ImdbDetails
    {
        public event Action<Movie> OnFinished;

        public bool Read(SearchMovieResult movie)
        {
            if(movie == null || movie.Id == null || string.IsNullOrEmpty(movie.Id))
            {
                return false;
            }

            var wf = new WebFetch(MovieUtils.GetMovieUrl(movie.Id));
            wf.OnFinished += wf_OnFinished;
            wf.Fetch(movie);

            return true;
        }

        private void wf_OnFinished(object sender, FetchEventArgs e)
        {
            const string regexPoster = "id=\"img_primary\">[\\n\\r\\s]*?<a[\\s]*?onclick[\\d\\D]*?href=\"[\\d\\D]*?<img src=\"([\\d\\D]*?)\"";
            var movieSearch = e.Data as SearchMovieResult;
            if(movieSearch == null)
            {
                return;
            }

            try
            {
                var movie = new Movie
                {
                    Title = movieSearch.Title,
                    Id = movieSearch.Id,
                    CoverWeb = Match(regexPoster, e.Result),
                    SeasonCount =
                        MatchAll("<a href=\"episodes#season-[\\d]*?\">([\\d]*?)</a>", e.Result).Max(
                            k => Int32.Parse(k)),
                    Season = 1
                };
                if (OnFinished != null)
                {
                    OnFinished(movie);
                }
            }
            catch(Exception exc)
            {
                ExceptionManager.ReportError(exc);
                if (OnFinished != null)
                {
                    OnFinished(null);
                }
            }
        }

        private static string Match(string regex, string html)
        {
            return new Regex(regex).Match(html).Groups[1].Value;
        }

        private static IEnumerable<string> MatchAll(string regex, string html, int i = 1)
        {
            return (from Match m in new Regex(regex, RegexOptions.Multiline).Matches(html) select m.Groups[i].Value).ToList();
        }
    }
}
